/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cafe.Controller;

import cafe.DataObject.Bill;
import cafe.DataObject.BillDetail;
import cafe.DataObject.Catalog;
import cafe.DataObject.Customer;
import cafe.DataObject.Food;
import cafe.Model.BillDetailModel;
import cafe.Model.BillModel;
import cafe.Model.CatalogModel;
import cafe.Model.CustomerModel;
import cafe.Model.FoodModel;
import hapax.TemplateDataDictionary;
import hapax.TemplateException;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.log.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author TieuHan
 */
public class BillController extends ControllerInterface {

    private static final org.eclipse.jetty.util.log.Logger LOG = Log.getLogger(BillController.class);
    BillModel billModel = BillModel.getInstance();

    @Override
    public String doAction(String action, HttpServletRequest request, HttpServletResponse response, String context) {

        switch (action) {
            case "additem":
                LOG.info("Add Bill");
                return addItem(request, response, context);
            case "getpageAdditem":
                return index(request, response, context, "/View/themhoadon.xtm");

            case "delete":
                LOG.info("Delete Bill");
                return delete(request, response, context);
            case "getitem":

                break;
            case "searchidbycustomer":
                LOG.info("Search Customer by ID");
                return Searchidbycustomer(request, response, context);
            case "listBillDetail":
                LOG.info("List Bill Detail");
                return listBillDetail(request, response, context);
            default:
                LOG.info("Default Bill Action: Index");
                return index(request, response, context, "/View/hoadon.xtm");
        }
        return "";

    }

    @Override
    public String index(HttpServletRequest request, HttpServletResponse response, String context, String URL) {

        List<Bill> cm = (List<Bill>) billModel.getAll();//Model

        for (Bill c : cm) {
            TemplateDataDictionary cmDic = templateCollection.getTemplateDataDictionary().addSection("Bill");
            cmDic.setVariable("Bill.Id", c.getId());
            cmDic.setVariable("Bill.Time", c.getDate().toString());
            cmDic.setVariable("Bill.TotalCost", String.valueOf(c.getTotalCost()));
            cmDic.setVariable("Bill.IsPaid", c.isPaid() == true ? "checked" : "");

            CustomerModel cus = CustomerModel.getInstance();
            Customer rs = cus.getByID(c.getCustomerId());

            cmDic.setVariable("Bill.customerName", rs.getName());
        }

        FoodModel Fm = FoodModel.getInstance();

        List<Food> f = (List<Food>) Fm.getAll();

        CatalogModel catalogModel = CatalogModel.getInstance();

        for (Food c : f) {
            TemplateDataDictionary cmDic1 = templateCollection.getTemplateDataDictionary().addSection("Food");

            cmDic1.setVariable("Food.id", c.getId());
            cmDic1.setVariable("Food.name", c.getName());
            cmDic1.setVariable("Food.Price", String.valueOf(c.getPrice()));
            cmDic1.setVariable("Food.Catagory", catalogModel.getByID(c.getCategoricalId()).getName());
        }

        //set variable to section
        return super.index(request, response, context, URL); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public String addItem(HttpServletRequest request, HttpServletResponse response, String context) {

        //id customer
        String id = request.getParameter("idcustomer-hidden");

        //Tao Json chu thong tin hoa don
        String result = request.getParameter("idFood");
        result = result.replace('[', '{');
        result = result.replace(']', '}');
        result = new StringBuffer(result).insert(1, "\"Foot\":[").toString();
        result = new StringBuffer(result).insert(result.length() - 1, "]").toString();
       
      
        long sum = Long.parseLong(request.getParameter("idTongTien"));

        Bill b = new Bill(new Date(), id, sum , true);
        BillModel bmm = BillModel.getInstance();
       
        int idHoaDon = bmm.insertWithAutoGeneratedKey(b);
       
       
        try {
            JSONObject jObject = new JSONObject(result);
            JSONArray jArray = jObject.getJSONArray("Foot");
            
            BillDetailModel BDM = BillDetailModel.getInstance();
            FoodModel fm = FoodModel.getInstance();
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject jObj = jArray.getJSONObject(i);
                
                BillDetail bd = new BillDetail();
                bd.setBillId(String.valueOf(idHoaDon));
                bd.setFoodId(String.valueOf(fm.getByName(jObj.getString("name")).getId()));
                
                bd.setAmount(jObj.getInt("value"));
                String price = jObj.getString("price");
                //bo chu VND ra khoi chuoi
                price = price.substring(0, price.length() - 4);
                bd.setPrice(Long.parseLong(price));
                BDM.insert(bd);
            }

        } catch (JSONException ex) {
            Logger.getLogger(BillController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return index(request, response, context, "/View/hoadon.xtm");
    }

    @Override
    public String delete(HttpServletRequest request, HttpServletResponse response, String context) {

        billModel.delete(request.getParameter("id"));
        return index(request, response, context, "/View/hoadon.xtm");
    }

    public String Searchidbycustomer(HttpServletRequest request, HttpServletResponse response, String context) {
        CustomerModel modelCM = CustomerModel.getInstance();
        Customer cm = modelCM.getByID(request.getParameter("id"));

        return "{\"name\":\"" + cm.getName() + "\",\"phone\":\"" + cm.getPhone() + "\"" + ",\"id\":\"" + cm.getId() + "\"" + "}";
    }

    public String renderPage(HttpServletRequest request, HttpServletResponse response, String context, String URL) {

        String id = (String) (request.getParameter("id") == null ? 1 : request.getParameter("id"));

        BillDetailModel billDetail = BillDetailModel.getInstance();

        List<BillDetail> listBill = (List<BillDetail>) billDetail.getByBillID(id);

        for (BillDetail bill : listBill) {
            FoodModel model = FoodModel.getInstance();
            Food food = model.getByID(bill.getFoodId());

            TemplateDataDictionary cmDic = templateCollection.getTemplateDataDictionary().addSection("Food");

            cmDic.setVariable("Food.name", food.getName());
            cmDic.setVariable("Food.amount", String.valueOf(bill.getAmount()));

            long value = food.getPrice() * bill.getAmount();

            cmDic.setVariable("Food.price", String.valueOf(value));
        }

        return super.index(request, response, context, URL);
    }

    public String listBillDetail(HttpServletRequest request, HttpServletResponse response, String context) {
        if (request.getParameter("do").equals("listBillDetail")) {
            
            
            return renderPage(request, response, context, "/View/chitiethoadon.xtm");
        } else {
            return index(request, response, context, "/View/hoadon.xtm");
        }
    }

   
}
